package com.sun.httpclient;

import org.junit.Test;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.StandardCharsets;


public class HttpURLConnTest {
    /**
     * jdk 原生API 请求网页
     */
    @Test
    public void test01() throws IOException {

        String urlStr = "https://www.baidu.com";
        URL url = new URL(urlStr);
        URLConnection connection = url.openConnection();
        HttpURLConnection httpURLConnection = (HttpURLConnection) connection;
        //设置请求类型
        /**
         * 请求行
         * 空格
         * 请求头
         * 请求体
         */
        httpURLConnection.setRequestMethod("GET");
        //
        httpURLConnection.setRequestProperty("Accept-Charset","utf-8");

        //获取httpURLConnection的输入流
        try(InputStream inputStream = httpURLConnection.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, StandardCharsets.UTF_8);
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader)
        ){
            String line;
            while ((line = bufferedReader.readLine()) != null){
                System.out.println(line);
            }

        }catch (Exception e){

        }
    }
}
